package com.useeinfo.oa.modules.security.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryData;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.data.TableResultData;
import com.useeinfo.framework.sugar.tools.AnalysisObjectList;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.security.dao.SystemUserDao;
import com.useeinfo.oa.modules.security.entity.*;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.security.vo.TreeSelectVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Author: 居泽平
 */
@Service("systemUserBizWeb")
public class SystemUserBiz extends CrudBiz<SystemUserDao, SystemUser> {

    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private SystemRoleBiz systemRoleBiz;
    @Autowired
    private UserRoleEnterpriseBiz userRoleEnterpriseBiz;
    @Autowired
    private SystemAuthorityBiz systemAuthorityBiz;
    @Autowired
    private UserDeviceBiz userDeviceBiz;

    public List<Object> getSystemUserByArea(String areaId, String enterpriseId,String authorityName, int pageNow, int pageSize, int type) {
        return dao.getSystemUserByArea(areaId, enterpriseId,authorityName, pageNow, pageSize, type);
    }
    public List<SelectVO> getSystemUserByOrgan(String organizationId) {
        return dao.getSystemUserByOrgan(organizationId);
    }
    public List<Long> getUserIdsByPosition(String positionId,String orgganizationId,String enterpriseId) {
        return dao.getUserIdsByPosition(positionId,orgganizationId,enterpriseId);
    }

    public ResultDto getNewAuth(Enterprise enterprise) {
        SystemUser systemUser = getLoginUser();
        List<GrantedAuthority> authorityList = new ArrayList<>();
        if ("enterprise".equals(systemUser.getOperationRole())) {
                String authHql = "select obj from SystemAuthority obj left join obj.systemModule as sm where obj.deleteStatus is false and ( sm is null  or" +
                        " sm.applicationModuleId in ( select al.id from  ApplicationModule al" +
                        " where exists( select ep from al.enterpriseSet ep where ep.id="+enterprise.getId()+")))";
                List<SystemAuthority>systemAuthorityList = systemAuthorityBiz.hqlExcute(authHql);
                for(SystemAuthority systemAuthority:systemAuthorityList){
                    authorityList.add(new SimpleGrantedAuthority(systemAuthority.getAuthorityName()));
                }
          /*  authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_AREA_EDIT"));//区域管理——新增编辑
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_AREA_LIST"));//区域管理——查看列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_GROUP_EDIT"));//设备分组管理——新增编辑
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_GROUP_LIST"));//设备分组管理——查看列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_CAT_EDIT"));//设备分类管理——新增编辑
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_CAT_LIST"));//设备分类管理——查看列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_EDIT"));//设备管理——新增编辑
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_LIST"));//设备管理——查看列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_IMPORT_EDIT"));//设备导入管理——新增编辑
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_IMPORT_LIST"));//设备导入管理——查看列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_REPAIR_ORDER_EDIT"));//维修单管理——新增编辑
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_REPAIR_ORDER_LIST"));//维修单管理——查看列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_REPAIR_ORDER_AUDIT_LIST"));//审批管理——查看列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_REPAIR_ORDER_AUDIT_EDIT"));//审批管理——查看列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_DATA_EDIT"));//设备资料--新增编辑
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_FACILITY_DATA_LIST"));// 设备资料--列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_DATA_CAT_EDIT"));//资料类型--新增编辑
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_DATA_CAT_LIST"));//资料类型--列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_TROUBLE_CAT_EDIT"));//故障分类管理
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_AUDIT_FLOW_EDIT"));//审批流管理
            authorityList.add(new SimpleGrantedAuthority("ROLE_ENTERPRISE_DICT_INFO_EDIT"));//数据字典管理
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_LIST"));//企业列表权限
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN_PERSONNEL_LIST"));//人员列表——部门管理
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN_PERSONNEL_EDIT"));//人员操作——部门管理
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN_ORGANIZATION_LIST"));//部门列表——部门管理
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN_ORGANIZATION_EDIT"));//部门编辑——部门管理
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN_POSITION_LIST"));//岗位列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN_POSITION_EDIT"));//岗位编辑
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_SYSTEM_USER_LIST"));//企业系统用户列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_SYSTEM_USER_EDIT"));//企业系统用户编辑
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_ROLE_LIST"));//企业系统角色列表
            authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN_ENTERPRISE_ROLE_EDIT"));//企业系统角色编辑*/
        }

        String authHql = "select obj from SystemAuthority obj left join obj.systemModule as sm where obj.deleteStatus is false and ( sm is null  or" +
                " sm.applicationModuleId                                             in ( select al.id from  ApplicationModule al" +
                " where exists( select ep from al.enterpriseSet ep where ep.id=" + enterprise.getId() + ")))" +
                " and exists( select r from obj.roleSet r where r.id in ( select ure.systemRole.id from UserRoleEnterprise ure where " +
                " ure.enterprise.id=" + enterprise.getId() + " and ure.systemUser.id =" + systemUser.getId() + ")) ";
        List<SystemAuthority> systemAuthorityList = systemAuthorityBiz.hqlExcute(authHql);

        // 新的权限


        for (SystemAuthority systemAuthority : systemAuthorityList) {
            authorityList.add(new SimpleGrantedAuthority(systemAuthority.getAuthorityName()));
        }

        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        //principal.setAuthorities(authorityList);

        // 重新new一个token，因为Authentication中的权限是不可变的.
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                principal, authentication.getCredentials(),
                authorityList);
        result.setDetails(authentication.getDetails());
        securityContext.setAuthentication(result);
        return ResultUtil.success();
    }

    public List<SystemUser> queryUser(String jpql, Map<String, Object> params) {

        return dao.findUser(jpql, params);
    }

    public Boolean existUserAccount(SystemUser systemUser) {
        //若用户名为空
        logger.info("用户名为：" + systemUser.getUserAccount());
        if (StringUtils.isBlank(systemUser.getUserAccount())) {
            return true;
        }

        //根据入库单号查询
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("userAccount", systemUser.getUserAccount());
        List<SystemUser> systemUserList = findList(queryParam);

        if (systemUser.getId() == null) {
            //新增操作，判断列表size是否为0
            return CollectionUtils.isNotEmpty(systemUserList);
        } else {
            //修改操作，情况一：判断list长度是否为1，并且与自身相同，那么就是不存在，所以结果取反
            //修改操作，情况二：判断list长度是0
            return !((systemUserList.size() == 1 && systemUserList.get(0).getId().equals(systemUser.getId())) || systemUserList.size() == 0);
        }
    }

    @Transactional
    public SystemUser getByUserAccount(String userAccount) {

        if (StringUtils.isBlank(userAccount)) {
            return null;
        }

        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("userAccount", userAccount);

        List<SystemUser> systemUserList = findList(queryParam);
        if (CollectionUtils.isEmpty(systemUserList)) {
            return null;
        }

        //查询结果串不为空，则返回第一个
        SystemUser systemUser = systemUserList.get(0);
        //logger.debug("systemRole:[{}]", systemUser.getSystemRole());

        return systemUser;
    }

    @Transactional
    public SystemUser getByUserAccount(String userAccount, boolean eager) {
        SystemUser user = getByUserAccount(userAccount);
        if (eager && user != null) {
            logger.info("" + user.getEnterpriseSet());
        }
        return user;
    }

    public List<SystemUser> findByRoleId(Long roleId) {
        return this.dao.findByRoleId(roleId);
    }

    @Transactional
    public void logicRemove(Long userId) {
        dao.logicRemove(userId);
    }

    public SystemUser getLoginUser() {

        SystemUser user = null;
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("userAccount", userDetails.getUsername());
        List<SystemUser> userList = dao.findList(queryParam);
        if (CollectionUtils.isNotEmpty(userList)) {
            user = userList.get(0);
        }
        return user;
    }

    public void removeEnterprise(Long userId) {
        dao.deleteEnterpriseByUserId(userId);
    }

    /**
     * 获取用户的项目
     *
     * @param userId
     * @return
     */
    public List<TreeSelectVO> getEnterpriseByUserId(Long userId, String sysCode) {
        List<TreeSelectVO> treeSelectVOS = new ArrayList<>();
        if (userId != null) {
            List objects = dao.getEnterpriseByUserId(userId);
            if (CollectionUtils.isNotEmpty(objects)) {
                for (Object object : objects) {
                    net.sf.json.JSONArray j = net.sf.json.JSONArray.fromObject(object);
                    treeSelectVOS.add(new TreeSelectVO(sysCode, AnalysisObjectList.getJsonString(j, 0)));
                }
            }
        }
        return treeSelectVOS;
    }

    /**
     * 添加公司
     *
     * @param userId
     */
    public void addEnterprise(Long userId, List<String> treesData) {
        if (CollectionUtils.isNotEmpty(treesData)) {
            SystemUser systemUser = findModel(userId);
            treesData.forEach(enterpriseId -> {
                Enterprise enterprise = enterpriseBiz.findModel(StringConverters.ToLong(enterpriseId));
                if (enterprise != null)
                    systemUser.addEnterprise(enterprise);
            });
        }
    }

    /**
     * 企业用户编辑保存
     *
     * @param enterprise 企业
     * @param id         用户id
     * @param passord    密码
     * @param roleId     角色id
     * @return
     */
    public ResultDto saveEdit(Enterprise enterprise, String id, String passord, String roleId) {
        if (enterprise == null) {
            return ResultUtil.error("公司不存在！");
        }
        SystemRole systemRole = systemRoleBiz.findModel(StringConverters.null2Long(roleId));
        if (systemRole == null) {
            return ResultUtil.error("角色不存在！");
        }
        SystemUser systemUser = dao.findModel(StringConverters.null2Long(id));
        if (systemUser == null) {
            return ResultUtil.error("用户不存在！");
        }
        //添加用户的角色
        systemUser.setUserPassword(passord);
        addOrUpdate(systemUser);
        //先移除用户此公司的角色
        List<UserRoleEnterprise> userRoleEnterprises = userRoleEnterpriseBiz.getUserRoleEnterpriseList(systemUser, null, enterprise);
        if (CollectionUtils.isNotEmpty(userRoleEnterprises)) {
            userRoleEnterprises.forEach(userRoleEnterprise -> userRoleEnterpriseBiz.delete(userRoleEnterprise.getId()));
        }
        //添加用户公司的角色
        userRoleEnterpriseBiz.addOrUpdate(new UserRoleEnterprise(systemRole, enterprise, systemUser));
        return ResultUtil.success();
    }

    /**
     * 用户查询
     *
     * @param queryParam 查询条件
     * @return
     */
    public JSONObject getSystemUserList(QueryParam queryParam, Enterprise enterprise) {
        List<SystemUser> systemUsers = this.findList(queryParam);
        if (CollectionUtils.isEmpty(systemUsers)) {
            return QueryData.nullReultJson(queryParam);
        }
        Long total = this.totalRecord(queryParam.getSqlMap());
        JSONArray rows = new JSONArray();
        systemUsers.forEach(systemUser -> {
            JSONObject jsonObject = systemUser.toJSONObject();
            List<UserRoleEnterprise> userRoleEnterprises = userRoleEnterpriseBiz.getUserRoleEnterpriseList(systemUser, null, enterprise);
            SystemRole role = new SystemRole();
            if (CollectionUtils.isNotEmpty(userRoleEnterprises)) {
                role = userRoleEnterprises.get(0).getSystemRole();
            }
            jsonObject.put("roleName", role.getRoleName());
            jsonObject.put("roleId", role.getId());
            rows.add(jsonObject);
        });
        return TableResultData.Rsult(total.intValue()
                , queryParam.getPageNow() == null ? 0 : queryParam.getPageNow()
                , queryParam.getPageSize() == null ? 0 : queryParam.getPageSize()
                , rows);
    }

    public ResultDto logout(HttpServletRequest request){
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        QueryParam queryParam = new QueryParam();
        assert systemUser != null && !org.springframework.util.StringUtils.isEmpty(systemUser);
        queryParam.getSqlMap().put("userId",systemUser.getId()+"");
        List<UserDevice> list = userDeviceBiz.findList(queryParam);
        for(UserDevice userDevice : list){
            userDeviceBiz.delete(userDevice.getId());
        }
        request.getSession().removeAttribute("LoginUser");
        request.getSession().removeAttribute("LoginEnterprise");
        request.getSession().invalidate();
        return ResultUtil.success();
    }



    /**
     * 用户账号密码登录接口
     *
     * @param userAccount
     * @param password
     * @return
     */
    public ResultDto login(HttpServletRequest request, String userAccount, String password, String deviceToken, String deviceType) {
        if (StringConverters.null2String(userAccount).equals("") || StringConverters.null2String(password).equals("")) {
            return ResultUtil.error("用户名或密码不可为空");
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("userAccount", userAccount);
        queryParam.getSqlMap().put("password", password);
        List<SystemUser> systemUserList = dao.findList(queryParam);
        if (CollectionUtils.isEmpty(systemUserList)) {
            return ResultUtil.error("请输入正确的用户名或密码");
        }

        SystemUser systemUser = systemUserList.get(0);
        systemUser.setUniqueid(UUID.randomUUID().toString());//每次登录变更用户唯一键，用于后面发送消息
        update(systemUser);
//        changeDeviceToken(systemUser, deviceToken, deviceType);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", systemUser.getId());
        jsonObject.put("userName", StringConverters.null2String(systemUser.getUserName()));
        jsonObject.put("workNO", StringConverters.null2String(systemUser.getWorkNo()));
        jsonObject.put("email", StringConverters.null2String(systemUser.getEmail()));
        jsonObject.put("mobile", StringConverters.null2String(systemUser.getMobile()));
        jsonObject.put("operationRole", StringConverters.null2String(systemUser.getOperationRole()));
        jsonObject.put("uniqueid", StringConverters.null2String(systemUser.getUniqueid()));
        Set<Enterprise> enterpriseSet = systemUser.getEnterpriseSet();
        JSONArray jsonArray = new JSONArray();
        JSONObject enterpriseJSON;
        for (Enterprise enterprise : enterpriseSet) {
            enterpriseJSON = new JSONObject();
            enterpriseJSON.put("id", enterprise.getId());
            enterpriseJSON.put("enterpriseName", StringConverters.null2String(enterprise.getEnterpriseName()));
            enterpriseJSON.put("enterpriseCode", StringConverters.null2String(enterprise.getCode()));
            jsonArray.add(enterpriseJSON);
        }
        jsonObject.put("enterprises", jsonArray);
        jsonObject.put("hostUrl", Configuration.getConfigurationByName("hostUrl"));
        SessionKeyUtils.setSessionUser(request,systemUser);
        request.getSession().setAttribute("LoginEnterprise", enterpriseSet.iterator().next());
        return ResultUtil.success(jsonObject);
    }

    /**
     * 登录记录设备
     *
     * @param uniqueid
     * @param deviceToken 设备token
     * @param deviceType
     * @return
     */
    public ResultDto userDeviceBinding(SystemUser systemUser,String uniqueid, String deviceToken, String deviceType) {
        if (StringConverters.null2String(uniqueid).equals("")) {
            return ResultUtil.error("登录信息不可为空");
        }
        if (StringConverters.null2String(deviceToken).equals("") || StringConverters.null2String(deviceType).equals("")) {
            return ResultUtil.error("设备Token不能为空");
        }
//        QueryParam queryParam = new QueryParam();
//        queryParam.getSqlMap().put("uniqueid", uniqueid);
//        List<SystemUser> systemUserList = dao.findList(queryParam);
//        if (CollectionUtils.isEmpty(systemUserList)) {
//            return ResultUtil.error("该账号不存在");
//        }
        if(!uniqueid.equals(systemUser.getUniqueid())){
            systemUser.setUniqueid(uniqueid);
        }

        //开始变更设备
        return changeDeviceToken(systemUser, deviceToken, deviceType);
    }

    /**
     * 开始变更用户设备
     *
     * @param systemUser  用户
     * @param deviceToken 设备token
     * @param deviceType  设备类型  ios / android
     * @return
     */
    public ResultDto changeDeviceToken(SystemUser systemUser, String deviceToken, String deviceType) {
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("userId", systemUser.getId().toString());
        List<UserDevice> userDevices = userDeviceBiz.findList(queryParam);//查询改设备token是否存在
        UserDevice userDevice;
        if (CollectionUtils.isNotEmpty(userDevices)) {
            userDevice = userDevices.get(0);
            userDevice.setDeviceToken(deviceToken);
            userDevice.setDeviceType(deviceType);
        } else {
            userDevice = new UserDevice(systemUser, deviceToken, deviceType);//都没有则new
        }
        userDeviceBiz.addOrUpdate(userDevice);
        return ResultUtil.success();
    }

    /**
     * 根据uniqueid获取用户登录信息
     *
     * @param uniqueid
     * @return
     */
    public ResultDto loginByUnique(String uniqueid, HttpServletRequest request) {
        if (StringConverters.null2String(uniqueid).equals("")) {
            return ResultUtil.error("登录信息不可为空");
        }
        SystemUser sessionUser=SessionKeyUtils.getSessionUser(request);
        if(sessionUser==null){
            return ResultUtil.error("登陆信息过期，请重新登陆");
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("uniqueid", uniqueid);
        List<SystemUser> systemUserList = dao.findList(queryParam);
        if (CollectionUtils.isEmpty(systemUserList)) {
            return ResultUtil.error("请重新登陆");
        }
        SystemUser systemUser = systemUserList.get(0);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", systemUser.getId());
        jsonObject.put("userName", StringConverters.null2String(systemUser.getUserName()));
        jsonObject.put("workNO", StringConverters.null2String(systemUser.getWorkNo()));
        jsonObject.put("email", StringConverters.null2String(systemUser.getEmail()));
        jsonObject.put("mobile", StringConverters.null2String(systemUser.getMobile()));
        jsonObject.put("operationRole", StringConverters.null2String(systemUser.getOperationRole()));
        jsonObject.put("uniqueid", StringConverters.null2String(systemUser.getUniqueid()));
        Set<Enterprise> enterpriseSet = systemUser.getEnterpriseSet();
        JSONArray jsonArray = new JSONArray();
        JSONObject enterpriseJSON;
        for (Enterprise enterprise : enterpriseSet) {
            enterpriseJSON = new JSONObject();
            enterpriseJSON.put("id", enterprise.getId());
            enterpriseJSON.put("enterpriseName", StringConverters.null2String(enterprise.getEnterpriseName()));
            enterpriseJSON.put("enterpriseCode", StringConverters.null2String(enterprise.getCode()));
            jsonArray.add(enterpriseJSON);
        }
        jsonObject.put("enterprises", jsonArray);
        jsonObject.put("hostUrl", Configuration.getConfigurationByName("hostUrl"));
        SessionKeyUtils.setSessionUser(request,systemUser);
        //SessionKeyUtils.setSessionEnterprise(request,enterpriseSet.iterator().next());
        return ResultUtil.success(jsonObject);
    }


    /**
     * 重置用户密码
     */
    public JSONObject resetPassword(String id) {
        JSONObject jsonObject = new JSONObject();
        SystemUser systemUser = dao.findModel(StringConverters.null2Long(id));
        if (null == systemUser) {
            jsonObject.put("result", "false");
            jsonObject.put("message", "用户信息有误");
            return jsonObject;
        }
        systemUser.setUserPassword("123456");
        dao.update(systemUser);
        jsonObject.put("result", "true");
        jsonObject.put("message", "成功");
        return jsonObject;
    }

    public List<SystemUser> hqlExcute(String hql, QueryParam queryParam) {
        return dao.hqlExcute(hql, queryParam);
    }
    public List<SystemUser> hqlExcute(String hql) {
        return dao.hqlExcute(hql);
    }
    /**
     * 根据区域获取人员列表
     *
     * @param areaId
     * @param enterpriseId
     * @return
     */
    /**
     *
     * @param areaId 任务区域id
     * @param enterpriseId 企业id
     * @param authorityName 任务单code
     * @param pageNow 分页
     * @param pageSize 分页
     * @param enterprise 企业参数
     * @return JSONObject
     */
    public JSONObject getSystemUserJson(String areaId, String enterpriseId,String authorityName, String pageNow, String pageSize,Enterprise enterprise) {
        int no = StringConverters.null2Int(pageNow);
        int size = StringConverters.null2Int(pageSize);
        List<Object> objects = dao.getSystemUserByArea(areaId, enterpriseId,authorityName, no, size, 0);
        JSONArray jsonArray = new JSONArray();
        if (objects != null) {
            objects.forEach(o -> {
                SystemUser systemUser = dao.findModel(StringConverters.null2Long(net.sf.json.JSONArray.fromObject(o).get(0)));

                List<UserRoleEnterprise> userRoleEnterprises = userRoleEnterpriseBiz.getUserRoleEnterpriseList(systemUser, null, enterprise);
                SystemRole role = new SystemRole();
                if (CollectionUtils.isNotEmpty(userRoleEnterprises)) {
                    role = userRoleEnterprises.get(0).getSystemRole();
                }
                JSONObject jsonObject=systemUser.toJSONObject();
                jsonObject.put("roleName",role.getRoleName());
                jsonArray.add(jsonObject);
            });
        }
        int count = StringConverters.null2Int(dao.getSystemUserByArea(areaId, enterpriseId,authorityName, no, size, 1).get(0));
        return TableResultData.Rsult(count, StringConverters.null2Int(pageNow), StringConverters.null2Int(pageSize), jsonArray);
    }


    /**
     * 通过企业id 获取 可选参与人员列表
     * @param queryParam 分页参数
     * @param enterprise 登陆者所属企业
     * @param userName 模糊查询 查找人名字
     * @return List<SystemUser>
     */
    public List<SystemUser> findParticipationUserByEnterprise(QueryParam queryParam, Enterprise enterprise, String userName) {
        // 分页参数
        Integer pageNow = queryParam.getPageNow();
        Integer pageSize = queryParam.getPageSize();
        List<Object> userLists = dao.findParticipationUserByEnterprise(pageNow,pageSize,enterprise.getId(),userName);
        return  null;

    }
}